package com.lagou.homework144;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerRunnable implements Runnable {

    ServerSocket serverSocket = null;
    Socket socket = null;
    BufferedReader bufferedReader;
    PrintStream printStream = null;
    ObjectOutputStream objectOutputStream = null;
    ObjectInputStream objectInputStream = null;

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(8888);
            System.out.println("---服务端：等待客户端连接...");
            socket = serverSocket.accept();
            System.out.println("---服务端：客户端连接成功！");
//            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            objectInputStream = new ObjectInputStream(socket.getInputStream());
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            while (true) {
                Object obj = objectInputStream.readObject();
                System.out.println("---服务端：收到客户端的消息 " + obj);
                if (obj instanceof UserMessage) {
                    User user = ((UserMessage) obj).getUser();
                    if (user.getUserName().equals("admin") && user.getPassword().equals("123456")) {
                        objectOutputStream.writeObject(new UserMessage("success", user));
                        break;
//                        socket.shutdownOutput();
                    } else
                        objectOutputStream.writeObject(new UserMessage("fail", user));
//                socket.shutdownOutput();
                }
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null)
                    socket.close();
                if (serverSocket != null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
